import styles from './index.module.css'
import {useRef,useEffect} from 'react'
import propTypes from 'prop-types'
const Sticky=(props)=>{
    const {height}=props
    // 创建ref对象
    const placeholder = useRef()
    const content = useRef()

    // scroll事件的事件处理程序
    const handleScroll=()=>{    
        // 获取ref对应的dom对象
        const placeholderEl=placeholder.current
        const contentEl=content.current

        const {top}=placeholderEl.getBoundingClientRect()
       
        if(top<0){
            placeholderEl.style.height=`${height}px`
            contentEl.classList.add(styles.fixed)
        }else{
            placeholderEl.style.height='0px'
            contentEl.classList.remove(styles.fixed)
        }
    }
    // 监听浏览器的scroll事件
    useEffect(()=>{
        window.addEventListener('scroll',handleScroll)


        // 组件卸载时执行
        return ()=>{
            window.removeEventListener('scroll',handleScroll)
        }
    },[])

    return(
        <div>
            {/* 占位元素 */}
            <div ref={placeholder}/>
            {/* 内容元素 */}
            <div ref={content}>{props.children}</div>
        </div>
    )    
}

Sticky.propTypes={
    height:propTypes.number.isRequired
}

export default Sticky